package com.atguigu.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * className: ServerSocketChannelDemo
 * description:
 * date: 2023/3/9 0009-14:45
 * <p>
 * project: nio
 * package: com.atguigu.channel
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class ServerSocketChannelDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 端口号
        int port = 8888;

        // buffer
        ByteBuffer buffer = ByteBuffer.wrap("hello atguigu".getBytes());

        // ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 绑定
        ssc.socket().bind(new InetSocketAddress(port));

        // 设置非阻塞模式
        ssc.configureBlocking(false);

        // 监听是否有新连接传入
        while (true) {
            System.out.println("Waiting for connections");
            SocketChannel sc = ssc.accept();
            if (sc == null) {
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
                // 指针指向 0
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        }
    }
}
